#!/usr/bin/env python
# coding=utf-8
"""
@Author  : youjia - 卞志伟
@file    : rclient.py
@contact : bianzhiwei@iyoujia.com
@time    : 2019-08-13 16:55 
@Desc    : 
@Software: PyCharm
"""
import os
import sys

# 当前文件的路径
pwd, filename = os.path.split(os.path.abspath(__file__))
# 当前文件的父路径
father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".")
# 当前文件的前两级目录
grader_father = os.path.abspath(os.path.dirname(pwd) + os.path.sep + "..")
sys.path.append(pwd)
sys.path.append(father_path)
sys.path.append(grader_father)
import requests, datetime, json, re
from hashlib import md5


class RClient(object):

    def __init__(self, username="iyoujia", password="iyoujia@2199"):
        self.username = username
        self.password = md5(password.encode()).hexdigest()
        self.soft_id = "114544"
        self.soft_key = "544dd57ce81c46098144f47cc5d05b9f"
        self.base_params = {
            'username': self.username,
            'password': self.password,
            'softid': self.soft_id,
            'softkey': self.soft_key,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'Expect': '100-continue',
            'User-Agent': 'ben',
        }

    def rk_create(self, im, im_type, timeout=60):
        """
        im: 图片字节
        im_type: 题目类型
        """
        params = {
            'typeid': im_type,
            'timeout': timeout,
        }
        # params1 = {
        #     'username': self.username,
        #     'password': self.password,
        # }

        params.update(self.base_params)
        files = {'image': ('VerifyImage.jpg', im)}
        # kd = requests.post('http://api.ruokuai.com/info.json', data=params1,)
        r = requests.post('http://api.ruokuai.com/create.json', data=params, files=files, headers=self.headers)
        return r.json()["Result"]

    def rk_report_error(self, im_id):
        """
        im_id:报错题目的ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://api.ruokuai.com/reporterror.json', data=params, headers=self.headers)
        return r.json()

    def rk_get_info(self):
        """
        查询用户信息
        """
        timestr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        boundary = '------------RK' + md5(timestr.encode("utf-8")).hexdigest().lower()
        boundarystr = '\r\n--%s\r\n' % (boundary)

        bs = b''
        for key, value in self.base_params.items():
            # print(key)
            # print(self.base_params[key])
            bs = bs + boundarystr.encode('ascii')
            param = "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s" % (key, value)
            # print(param)
            bs = bs + param.encode('utf8')
        bs = bs + boundarystr.encode('ascii')

        header = 'Content-Disposition: form-data; name=\"image\"; filename=\"%s\"\r\nContent-Type: image/gif\r\n\r\n' % (
            'sample')
        bs = bs + header.encode('utf8')

        tailer = '\r\n--%s--\r\n' % (boundary)
        bs = bs + tailer.encode('ascii')

        import requests
        headers = {'Content-Type': 'multipart/form-data; boundary=%s' % boundary,
                   'Connection': 'Keep-Alive',
                   'Expect': '100-continue',
                   }
        response = requests.post("http://api.ruokuai.com/info.json", params='', data=bs, headers=headers)
        # 返回剩余快豆
        score = json.loads(response.text)
        return score["Score"]


def tujia_token(login_name="17710393959", password="youjiatujia"):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
    }
    proxies = {
        'http': 'http://H4D3E584VRA2842D:7CCD05274100107A@http-dyn.abuyun.com:9020',
        'https': 'http://H4D3E584VRA2842D:7CCD05274100107A@http-dyn.abuyun.com:9020',
    }
    img_file = "VerifyImage.jpg"
    session = requests.session()
    img = session.get("https://passport.tujia.com/Landlord/VerifyImage", verify=False)
    with open(img_file, "wb") as f:
        f.write(img.content)

    # 查看账户余额
    rc = RClient()
    print(rc.rk_get_info())
    if int(rc.rk_get_info()) > 30:
        im = open("VerifyImage.jpg", "rb").read()
        # 识别图片验证码
        tujia_code = rc.rk_create(im, 8000)
        data = {"LoginName": login_name,
                "Password": password,
                "VerifyCode": tujia_code}

        tujia_header = session.post("https://passport.tujia.com/Landlord/AjaxLogin", data=data,
                                    headers=headers,
                                    proxies=proxies)

        print(tujia_header.headers)
        tujia_token = re.compile(r"UserToken=(.*?);")
        tujia_token = tujia_token.findall(str(tujia_header.headers))
        try:
            return tujia_token[0]
        except:
            return tujia_token(login_name, password)
